package bookmanagementsystem.dao;

import bookmanagementsystem.model.Book;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.sql.Timestamp;

public class BookDAO {
    private static final String URL = "jdbc:mysql://localhost:3306/book_management_system";
    static final String USERNAME = "root";
    static final String PASSWORD = "root";

    // 添加图书方法，修改此处实现入库时间自动生成
    public boolean addBook(Book book) {
        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
             PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO book_table (book_id, book_name, author_name, entry_time, quantity_in_library, location) VALUES (?,?,?,?,?,?)")) {

            preparedStatement.setString(1, book.getBookID());
            preparedStatement.setString(2, book.getBookName());
            preparedStatement.setString(3, book.getAuthorName());
            // 获取当前时间作为入库时间，自动生成时间逻辑
            Timestamp currentTime = new Timestamp(System.currentTimeMillis());
            preparedStatement.setTimestamp(4, currentTime);
            preparedStatement.setInt(5, book.getQuantityInLibrary());
            preparedStatement.setString(6, book.getLocation());

            int rowsAffected = preparedStatement.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            // 更详细的异常处理，区分不同的错误情况并给出相应提示（示例，可根据实际数据库错误码完善）
            e.printStackTrace();
            return false;
        }
    }

    // 根据图书ID查询图书方法
    public Book queryBookById(String bookID) {
        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
             PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM book_table WHERE book_id =?")) {

            preparedStatement.setString(1, bookID);

            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                String bookName = resultSet.getString("book_name");
                String authorName = resultSet.getString("author_name");
                Timestamp entryTime = resultSet.getTimestamp("entry_time");
                int quantityInLibrary = resultSet.getInt("quantity_in_library");
                String location = resultSet.getString("location");

                return new Book(bookID, bookName, authorName, entryTime, quantityInLibrary, location);
            }

            return null;
        } catch (SQLException e) {
            System.out.println("根据图书ID查询图书时出错：" + e.getMessage());
            return null;
        }
    }

    // 根据图书名称查询图书方法
    public Book queryBookByName(String bookName) {
        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
             PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM book_table WHERE book_name =?")) {
            bookName = bookName.trim();
            preparedStatement.setString(1, bookName);

            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                String bookID = resultSet.getString("book_id");
                String authorName = resultSet.getString("author_name");
                Timestamp entryTime = resultSet.getTimestamp("entry_time");
                int quantityInLibrary = resultSet.getInt("quantity_in_library");
                String location = resultSet.getString("location");

                return new Book(bookID, bookName, authorName, entryTime, quantityInLibrary, location);
            }

            return null;
        } catch (SQLException e) {
            System.out.println("根据图书名称查询图书时出错：" + e.getMessage());
            return null;
        }
    }




    // 根据作者姓名查询图书方法

    // 查询所有图书方法
    public List<Book> queryAllBooks() {
        List<Book> books = new ArrayList<>();
        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
             PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM book_table")) {

            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                String bookID = resultSet.getString("book_id");
                String bookName = resultSet.getString("book_name");
                String authorName = resultSet.getString("author_name");
                Timestamp entryTime = resultSet.getTimestamp("entry_time");
                int quantityInLibrary = resultSet.getInt("quantity_in_library");
                String location = resultSet.getString("location");

                books.add(new Book(bookID, bookName, authorName, entryTime, quantityInLibrary, location));
            }

            return books;
        } catch (SQLException e) {
            System.out.println("查询所有图书时出错：" + e.getMessage());
            return null;
        }
    }

    // 删除图书方法
    public boolean deleteBook(String bookID) {
        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
             PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM book_table WHERE book_id =?")) {

            preparedStatement.setString(1, bookID);

            int rowsAffected = preparedStatement.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            System.out.println("删除图书时出错：" + e.getMessage());
            return false;
        }
    }

    // 更新图书库存数量方法
    public boolean updateBookQuantity(String bookID, int newQuantity) {
        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
             PreparedStatement preparedStatement = connection.prepareStatement("UPDATE book_table SET quantity_in_library =? WHERE book_id =?")) {

            preparedStatement.setInt(1, newQuantity);
            preparedStatement.setString(2, bookID);

            int rowsAffected = preparedStatement.executeUpdate ();
            return rowsAffected > 0;
        } catch (SQLException e) {
            System.out.println("更新图书库存数量时出错：" + e.getMessage());
            return false;
        }
    }

    // 更新图书信息方法（包括图书名称、作者、库存数量、存放位置等）
    public boolean updateBookInfo(Book book) {
        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
             PreparedStatement preparedStatement = connection.prepareStatement("UPDATE book_table SET book_name =?, author_name =?, quantity_in_library =?, location =? WHERE book_id =?")) {

            preparedStatement.setString(1, book.getBookName());
            preparedStatement.setString(2, book.getAuthorName());
            preparedStatement.setInt(3, book.getQuantityInLibrary());
            preparedStatement.setString(4, book.getLocation());
            preparedStatement.setString(5, book.getBookID());

            int rowsAffected = preparedStatement.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            System.out.println("更新图书信息时出错：" + e.getMessage());
            return false;
        }
    }
}